<button type="button" class="layui-btn layui-btn-danger" onclick="batchDeleteStudents()">批量删除</button>
<button type="button" class="layui-btn" onclick="addStudent()">新增学生信息</button>
<button type="button" class="layui-btn" onclick="batchImport()">批量导入</button>
<div id="uploadFile" style="display: inline-block;"></div>
<div id="importTemplateDown" style="display: inline-block;"></div>
<table id="student-info"></table>

<div id="add-student" style="display: none;">
	<form class="layui-form" id="add-form" lay-filter="add-form">
		<div class="layui-form-item">
			<label class="layui-form-label">学生姓名</label>
			<div class="layui-input-block">
				<input type="text" name="studentName" placeholder="请输入学生姓名" class="layui-input">
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label">所属老师</label>
			<div class="layui-input-block" id="add-this">
				<select name="teacherNo" id="add-select-teacher">

				</select>
			</div>
		</div>
	</form>
</div>
<div id="edit-student" style="display: none;">
	<form class="layui-form" id="edit-form" lay-filter="edit-form">
		<div class="layui-form-item">
			<label class="layui-form-label">学生编号</label>
			<div class="layui-input-block">
				<input type="text" id="studentNo" name="studentNo" readonly="readonly" class="layui-input">
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label">学生姓名</label>
			<div class="layui-input-block">
				<input type="text" id="studentName" name="studentName" class="layui-input">
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label">所属老师</label>
			<div class="layui-input-block" id="edit-this">
				<select name="teacherNo" id="edit-select-teacher">
				</select>
			</div>
		</div>
	</form>
</div>
<script>
	layui.use(["form", "table", "layer", "upload"], function (form, table, layer, upload) {
		table.render({
			elem: '#student-info',
			height: 480,
			url: serverPath + "/students",
			headers: {
				"auth-token": getToken()
			},
			//res 即为原始返回的数据
			parseData: function (res) {
				return {
					"code": res.data.code,
					"count": res.data.count,
					"data": res.data.data
				};
			},
			cols: [
				[{
					field: '',
					title: '',
					align: "center",
					type: "checkbox"
				},
				{
					field: 'studentNo',
					title: '学生编号',
					align: "center"
				},
				{
					field: 'studentName',
					title: '学生姓名',
					align: "center"
				},
				{
					field: 'teacherName',
					title: '教师姓名',
					align: "center"
				},
				{
					field: '',
					title: '操作',
					align: "center",
					templet: function (row) {
						return `
                        <button type="button" class="layui-btn layui-btn-normal" studentNo="${row.studentNo}" onclick="editStudent(this)" student-name="${row.studentName}">修改</button>
                        <button type="button" class="layui-btn layui-btn-danger" onclick="deleteStudent(${row.studentNo})">删除</button>`;
					}
				}
				]
			],
			page: true,
			page: {
				limit: 5,
				limits: [5, 10, 15, 20]
			},
			done: function (res, curr, count) {
				if (curr > 1 && null == res.data) {
					curr = curr - 1;
					table.reload('student-info', {
						//设定异步数据接口的额外参数，任意设
						where: {},
						page: {
							curr: curr
						}
					});
				}
			}
		});

		var roles = instance.defaults.userRoles;

		//根据权限选择老师
		if ($.inArray("ROLE_ADMIN", roles) != -1) {
			axios.get(serverPath + "/teachers?page=-1&limit=-1", {
				headers: {
					"auth-token": getToken()
				}
			}).then(function (response) {
				var teachers = response.data.data.data;
				$.each(teachers, function () {
					$("#add-select-teacher").append(
						`
                <option value="${this.teacherNo}">${this.teacherNo}${this.teacherName}</option>		
				`);
					$("#edit-select-teacher").append(
						`
                <option value="${this.teacherNo}">${this.teacherNo}<span>${this.teacherName}</span></option>		
				`
					);
				});
			});
		} else if ($.inArray("ROLE_TEACHER", roles) != -1) {
			$("#add-select-teacher").empty();
			$("#add-this").html('<input type="text" name="teacherName" value="当前老师" class="layui-input" readonly="readonly">');
			$("#edit-select-teacher").empty();
			$("#edit-this").html('<input type="text" name="teacherName" value="当前老师" class="layui-input" readonly="readonly">');
		}
		//批量导入
		window.batchImport = function () {
			//这里的pathName 就是上传的Excel模板路径
			var pathName = "学生信息模板.xlsx";
			axios.get(serverPath + "/teachers", {
				params: {
					pathName: pathName
				},
				headers: {
					"auth-token": getToken()
				}
			}).then(function (response) {
				table.reload("student-info");
				layer.confirm(response.data.data, function () {
					layer.closeAll();
				})
			}).catch(function (error) {
				layer.alert(error.response.data.error)
			});
		}

		//导入模板下载
		window.importTemplateDown = function () {
			var fileName = localStorage.getItem("upload-file-name");
			if (null == fileName || "" == fileName) {
				layer.alert("请联系管理员上传Excel模板");
			} else {
				localStorage.removeItem("upload-file-name");
				location.href = serverPath + "/download?fileName=" + fileName;
			}
		}

		//上传组件 上传Excel模板
		var uploadInst = upload.render({
			elem: '#upload',
			url: serverPath + '/upload',
			headers: {
				"auth-token": getToken()
			},
			//文件域的名字
			field: "file",
			//下面三行设置文件只能是xls或xlsx形式
			accept: "file",
			acceptMime: "application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
			exts: "xls|xlsx",
			done: function (res) {
				console.log(res)
				if (res.code == 200) {
					layer.alert("上传成功!");
				}
				// 管理员上传Excel模板的带分组的路径
				console.log("上传Excel模板的带分组的路径:" + res.data[0]);
				localStorage.setItem("upload-file-name", res.data[0])
			},
			error: function () {
				layer.alert("上传错误");
			}
		});

		//新增学生
		window.addStudent = function (studentNo) {
			layer.open({
				type: 1,
				title: "新增学生",
				area: ["500px", "350px"],
				content: $("#add-student"),
				btn: ['确认', "取消"],
				btnAlign: 'c',
				yes: function (index, layero) {
					var addData = form.val("add-form");
					var studentName = addData.studentName;
					if ($.inArray("ROLE_ADMIN", roles) != -1) {
						var teacherNo = addData.teacherNo.replace(/\b(0+)/gi, "");
						axios.post(serverPath + "/students", {
							studentName: studentName,
							teacherNo: teacherNo,
						}, {
							headers: {
								"auth-token": getToken()
							}
						}).then(function (response) {
							resetForm();
							table.reload("student-info");
							layer.confirm(response.data.data, function () {
								layer.closeAll();
							})
						})
							.catch(function (error) {
								layer.alert(error.response.data.error)
							});
					} else if ($.inArray("ROLE_TEACHER", roles) != -1) {
						var teacherNo = instance.defaults.userId;
						axios.post(serverPath + "/teachers/" + teacherNo, {
							studentName: studentName
						}, {
							headers: {
								"auth-token": getToken()
							}
						}).then(function (response) {
							resetForm();
							table.reload("student-info");
							layer.confirm(response.data.data, function () {
								layer.closeAll();
							})
						})
							.catch(function (error) {
								layer.alert(error.response.data.error)
							});
					}
				},
				success: function () {
					form.render();
				},
				btn2: function (index, layero) {
					layer.confirm("是否退出", function (index) {
						layer.closeAll();
					})
					return false;
				}
			});

		};
		//修改学生
		window.editStudent = function (target) {
			//获取学生的修改信息
			var studentNo = $(target).attr("studentNo");
			var studentName = $(target).attr("student-name");
			$("#studentNo").val(studentNo);
			$("#studentName").val(studentName);
			//获取当前学生的老师编号
			axios.get(serverPath + "/students/" + studentNo, {
				headers: {
					"auth-token": getToken()
				}
			}).then(function (response) {
				var curTeacherNo = response.data.data.teacherNo;
				//弹出的学生所属老师应为当前学生的所属老师 '" + curTeacherNo + "'
				$("#edit-select-teacher").find("option[value = '" + curTeacherNo + "']").attr("selected", "selected");
				//下面操作可以得到下拉框中的所有选项的值
				// var options = $("#edit-select-teacher>option").map(function () { return $(this).val(); }).get();
				layer.open({
					type: 1,
					title: "修改学生",
					area: ["500px", "350px"],
					content: $("#edit-student"),
					btn: ['确认', "取消"],
					btnAlign: 'c',
					yes: function (index, layero) {
						var editData = form.val("edit-form");
						var teacherNo = editData.teacherNo;
						if (studentName == editData.studentName && curTeacherNo == teacherNo) {
							layer.alert("您当前还没有修改任何信息...");
						} else {
							// //重新复制学生的名称
							studentName = editData.studentName;
							//发送修改学生信息的请求
							axios.put(serverPath + "/students/" + editData.studentNo, {
								studentName: studentName,
								teacherNo: teacherNo
							}, {
								headers: {
									"auth-token": getToken()
								}
							}).then(function (response) {
								//成功后关闭上一个弹窗
								layer.close(index);
								resetForm();
								table.reload("student-info");
								layer.confirm(response.data.data, function () {
									layer.closeAll();
								})
							}).catch(function (error) {
								layer.alert(error.response.data.error);
							});
						}
					},
					success: function () {
						form.render();
					},
					btn2: function (index, layero) {
						layer.confirm("是否退出", function (index) {
							layer.closeAll();
						})
						return false;
					}
				});
			});
		};

		//删除一个学生
		window.deleteStudent = function (studentNo) {
			deleteAny(studentNo, (serverPath + "/students"), "student-info")
		};

		//批量删除学生
		window.batchDeleteStudents = function () {
			var checkStatus = table.checkStatus('student-info');
			var checkData = checkStatus.data;
			var studentNos = $.map(checkData, function (obj) {
				console.log(obj)
				return obj.studentNo;
			});
			if (studentNos.length < 2) {
				layer.alert("请至少选择两条数据");
				return;
			}
			deleteAny(studentNos, (serverPath + "/students"), "student-info")
			table.reload("student-info");
		};

		//重置表单
		function resetForm() {
			document.getElementById("add-form").reset();
			document.getElementById("edit-form").reset();
		}
	})
</script>